from routes import db
from models.vep_model import VepParameter, VepResult
# from sqlalchemy.exc import IntegrityError


class VepService:
    # VepParameter 的增删改查逻辑
    def add_vep_parameter(self, data):
        vep_parameter = VepParameter(**data)
        db.session.add(vep_parameter)
        db.session.commit()
        return vep_parameter

    def update_vep_parameter(self, id, data):
        vep_parameter = VepParameter.query.get(id)
        if vep_parameter:
            for key, value in data.items():
                setattr(vep_parameter, key, value)
            db.session.commit()
            return vep_parameter
        return None

    def delete_vep_parameter(self, id):
        vep_parameter = VepParameter.query.get(id)
        if vep_parameter:
            db.session.delete(vep_parameter)
            db.session.commit()
            return True
        return False

    def get_vep_parameter(self, id):
        return VepParameter.query.get(id)

    def get_all_vep_parameters(self):
        return VepParameter.query.all()

    # VepResult 的增删改查逻辑
    def add_vep_result(self, data):
        vep_result = VepResult(**data)
        db.session.add(vep_result)
        db.session.commit()
        return vep_result

    def update_vep_result(self, id, data):
        vep_result = VepResult.query.get(id)
        if vep_result:
            for key, value in data.items():
                setattr(vep_result, key, value)
            db.session.commit()
            return vep_result
        return None

    def delete_vep_result(self, id):
        vep_result = VepResult.query.get(id)
        if vep_result:
            db.session.delete(vep_result)
            db.session.commit()
            return True
        return False

    def get_vep_result(self, id):
        return VepResult.query.get(id)

    def get_all_vep_results(self):
        return VepResult.query.all()

    def get_vep_parameter_by_fields(self, year, city, district, town, vepname):
        return VepParameter.query.filter_by(
            year=year,
            vepName=vepname,
            vepCity=city,
            vepDistrict=district,
            vepTown=town
        ).first()

    def get_vep_result_by_fields(self, year, city, district, town, vepname):
        return VepResult.query.filter_by(
            year=year,
            vepName=vepname,
            vepCity=city,
            vepDistrict=district,
            vepTown=town
        ).first()

    def add_vep_parameter_by_fields(self, data):
        existing = self.get_vep_parameter_by_fields(data['year'],data['vepCity'], data['vepDistrict'], data['vepTown'], data['vepName'])
        if existing:
            raise ValueError("Record already exists")
        vep_parameter = VepParameter(**data)
        db.session.add(vep_parameter)
        db.session.commit()
        return vep_parameter

    def add_vep_result_by_fields(self, data):
        existing = self.get_vep_result_by_fields(data['year'],data['vepCity'], data['vepDistrict'], data['vepTown'], data['vepName'])
        if existing:
            raise ValueError("Record already exists")
        vep_result = VepResult(**data)
        db.session.add(vep_result)
        db.session.commit()
        return vep_result

    def update_vep_parameter_by_fields(self, year, city, district, town, vepname, update_data):
        # 1. 查询是否存在该记录
        record = self.get_vep_parameter_by_fields(year, city, district, town, vepname)
        # print("update_vep_parameter_by_fields-town",town)
        if not record:
            # 2. 如果不存在，则创建新记录，并从 update_data 中提取所有合法字段
            record = VepParameter(
                year=year,
                vepCity=city,
                vepDistrict=district,
                vepTown=town,
                vepName=vepname,
                **{k: v for k, v in update_data.items() if k not in ['year', 'city', 'district', 'town']}
            )
        else:
            # 3. 如果存在，则仅更新传入的字段（避免覆盖已有数据）
            for key, value in update_data.items():
                setattr(record, key, value)

        # 4. 提交更改或新增
        db.session.add(record)
        db.session.commit()
        return record

        # record = self.get_vep_parameter_by_fields(year, city, district, town, vepname)
        # if not record:
        #     return None
        # for key, value in data.items():
        #     setattr(record, key, value)
        # db.session.commit()
        # return record

    def update_vep_result_by_fields(self, year, city, district, town, vepname, update_data):
        # 1. 查询是否存在该记录
        record = self.get_vep_result_by_fields(year, city, district, town, vepname)
        # print("update_vep_result_by_fields-town",town)

        if not record:
            # 2. 如果不存在，则创建新记录，并从 update_data 中提取所有合法字段
            record = VepResult(
                year=year,
                vepCity=city,
                vepDistrict=district,
                vepTown=town,
                vepName=vepname,
                **{k: v for k, v in update_data.items() if k not in ['year', 'city', 'district', 'town']}
            )
        else:
            # 3. 如果存在，则仅更新传入的字段（避免覆盖已有数据）
            for key, value in update_data.items():
                setattr(record, key, value)

        # 4. 提交更改或新增
        db.session.add(record)
        db.session.commit()
        return record

        # record = self.get_vep_result_by_fields(year, city, district, town, vepname)
        # if not record:
        #     return None
        # for key, value in data.items():
        #     setattr(record, key, value)
        # db.session.commit()
        # return record

    def delete_vep_parameter_by_fields(self, year, city, district, town, vepname):
        record = self.get_vep_parameter_by_fields(year, city, district, town, vepname)
        if not record:
            return False
        db.session.delete(record)
        db.session.commit()
        return True

    def delete_vep_result_by_fields(self, year, city, district, town, vepname):
        record = self.get_vep_result_by_fields(year, city, district, town, vepname)
        if not record:
            return False
        db.session.delete(record)
        db.session.commit()
        return True
